﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DailyRssDownload.Lib;
using DailyRssDownload.UI;

namespace DailyRssDownload.UI {
	public partial class DailyRssDownloadSettings : BaseForm {
		public Settings CurrentSettings { get;	set; }
		private List<Feed> SortedFeeds { get; set; }

		public void LoadState() {
			txtDownloadLocation.Text = CurrentSettings.DownloadLocation;
			cbOnlyDownloadNewContent.Checked = CurrentSettings.OnlyDownloadNewContent;

			IEnumerable<Feed> lstFeeds = from feed in CurrentSettings.Feeds
										 orderby feed.DisplayOrder
										 select feed;
			SortedFeeds = new List<Feed>(CurrentSettings.Feeds.Count);
			foreach (Feed objFeed in lstFeeds)
				SortedFeeds.Add(objFeed);

			feedBindingSource.DataSource = SortedFeeds;
		}

		public DailyRssDownloadSettings() {
			InitializeComponent();

			CurrentSettings = new Settings();
			LoadState();
		}

        private void cmdDownloadLocation_Click(object sender, EventArgs e) {
            DialogResult objResult = folderBrowserDialog1.ShowDialog();
            if (objResult == DialogResult.OK) {
				txtDownloadLocation.Text = folderBrowserDialog1.SelectedPath;
				CurrentSettings.DownloadLocation = folderBrowserDialog1.SelectedPath;
				CurrentSettings.Save();
            }
        }

        private void cmdSave_Click(object sender, EventArgs e) {
			this.Close();
			this.Dispose();
        }

		private void cmdCancel_Click(object sender, EventArgs e) {
			this.Close();
			this.Dispose();
		}

		private void cmdDownloadNow_Click(object sender, EventArgs e) {
			Newspaper objConnection = new Newspaper(this.CurrentSettings);
			objConnection.BackgroundWorker = _backgroundWorker;
			_backgroundWorker.RunWorkerAsync(objConnection);
			cmdDownloadNow.Enabled = false;

			//while (_backgroundWorker.IsBusy) {
			//    // Keep UI messages moving, so the form remains 
			//    // responsive during the asynchronous operation.
			//    Application.DoEvents();
			//}
		}

		private void cmdAddFeed_Click(object sender, EventArgs e) {
			int intFeedCount = feedBindingSource.Count;

			Feed objFeed = Feed.CreateFeed(txtNewFeedUrl.Text, intFeedCount);

			// try to populate the title by hitting the Internet
			if (objFeed == null) {
				MessageBox.Show("An error occurred connecting to the URL you entered.");
			} else {
				feedBindingSource.Add(objFeed);
				CurrentSettings.Feeds.Add(objFeed);
				CurrentSettings.Save();
			}
		}

		private void dgRssFeeds_SelectionChanged(object sender, EventArgs e) {
			cmdDeleteFeed.Enabled = true;
		}

		private void cmdDeleteFeed_Click(object sender, EventArgs e) {
			foreach (DataGridViewRow row in dgRssFeeds.Rows) {
				if (row.Selected) {
					CurrentSettings.Feeds.Remove((Feed)row.DataBoundItem);
					feedBindingSource.Remove(row.DataBoundItem);
				}
			}
			CurrentSettings.Save();
		}

		private void cmdSetSchedule_Click(object sender, EventArgs e) {
			MessageBox.Show("Scheduling is not currently supported within the config application.  Instead create a recurring task to execute the command \"DailyRssDownload.exe DownloadNow\" from within scheduled events in your control panel.");
		}

		private void cbOnlyDownloadNewContent_CheckedChanged(object sender, EventArgs e) {
			CurrentSettings.OnlyDownloadNewContent = cbOnlyDownloadNewContent.Checked;
			CurrentSettings.Save();
		}

		private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e) {
			Newspaper objNewspaper = (Newspaper)e.Argument;
			objNewspaper.DownloadNow();
		}

		private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
			// The download is done, so enable the button.
			cmdDownloadNow.Enabled = true;

			// load state in case anything changed after downloading (like if we should download new content)
			LoadState();
			
			if (e.Error == null) {
				MessageBox.Show("Download complete.");
			} else {
				MessageBox.Show("An error occurred while downloading.  Check the log for more details");
				Log.LogError(e.Error);
			}
		}

		private void _backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
			toolStripProgressBar1.Value = e.ProgressPercentage;
			toolStripStatusLabel1.Text = e.UserState.ToString();
		}

		private void dgRssFeeds_CellClick(object sender, DataGridViewCellEventArgs e) {
			if (e.RowIndex >= 0) {
				Feed objFeedSelected = (Feed)feedBindingSource[e.RowIndex];
				FeedSettings frmFeedSettings = new FeedSettings(objFeedSelected);
				DialogResult objResult = frmFeedSettings.ShowDialog();
				CurrentSettings.Save();
			}
		}


    }
}
